package com.qishanor.wpan.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qishanor.framework.common.oss.config.FileProperties;
import com.qishanor.framework.common.oss.service.FileTemplate;
import com.qishanor.framework.util.R;
import com.qishanor.wpan.mapper.WpanFileMapper;
import com.qishanor.wpan.model.WpanFile;
import com.qishanor.wpan.service.WpanFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: 周振林
 * @date: 2023-05-24
 * @website: http://www.zhouzhenlin.com - 沉淀、分享、成长、让自己和他人都有所收获
 **/

@Service
public class WpanFileServiceImpl extends ServiceImpl<WpanFileMapper, WpanFile> implements WpanFileService {

    @Autowired
    private FileTemplate fileTemplate;
    @Autowired
    private FileProperties properties;


    @Override
    public R uploadFile(MultipartFile file) {
        String fileName = IdUtil.simpleUUID() + StrUtil.DOT + FileUtil.extName(file.getOriginalFilename());
//        Map<String, String> resultMap = new HashMap<>(4);
//        resultMap.put("bucketName", properties.getBucketName());
//        resultMap.put("fileName", fileName);
//        resultMap.put("url", String.format("/sys/file/%s/%s", properties.getBucketName(), fileName));

        try (InputStream inputStream = file.getInputStream()) {
            fileTemplate.putObject(properties.getBucketName(), fileName, inputStream, file.getContentType());
        }
        catch (Exception e) {
            log.error("上传失败", e);
            return R.failed(e.getLocalizedMessage());
        }

        WpanFile wpanFile=WpanFile.builder()
                .dirType("0")
                .dirParent(-1L)
                .realName(file.getOriginalFilename())
                .finalName(fileName)
                .category("")
                .url("/"+fileName)
                .size(Convert.toStr(file.getSize()))
                 .type(FileUtil.extName(file.getOriginalFilename()))
                .build();
        this.save(wpanFile);

        return R.ok();
    }
}
